class AppManager {
    constructor() {
        this.appContainer = document.getElementById('app-container');
        this.mainTitle = document.getElementById('main-title');
        this.subtitle = document.getElementById('subtitle');

        this.init();
    }

    init() {
        if (!window.config) {
            this.showError('配置文件加载失败');
            return;
        }

        this.loadConfig();
        this.renderApps();
    }

    loadConfig() {
        const { title, subtitle, theme } = window.config;

        if (title) {
            this.mainTitle.textContent = title;
        }

        if (subtitle) {
            this.subtitle.textContent = subtitle;
        }

        if (theme) {
            this.applyTheme(theme);
        }
    }

    applyTheme(theme) {
        const root = document.documentElement;

        if (theme.primaryColor) {
            root.style.setProperty('--primary-color', theme.primaryColor);
        }

        if (theme.secondaryColor) {
            root.style.setProperty('--secondary-color', theme.secondaryColor);
        }

        if (theme.backgroundColor) {
            document.body.style.backgroundColor = theme.backgroundColor;
        }
    }

    renderApps() {
        const apps = window.config.apps || [];

        if (apps.length === 0) {
            this.showEmptyState();
            return;
        }

        this.appContainer.innerHTML = '';

        apps.forEach((app, index) => {
            const appCard = this.createAppCard(app, index);
            this.appContainer.appendChild(appCard);
        });
    }

    createAppCard(app, index) {
        const card = document.createElement('a');
        card.href = app.url;
        card.className = 'app-card';
        card.target = '_blank';
        card.rel = 'noopener noreferrer';

        card.innerHTML = `
            <div class="app-icon">${this.getAppIcon(app.name, index)}</div>
            <h3>${app.name}</h3>
            <p>${app.description || '暂无描述'}</p>
            <span class="app-link">进入应用 →</span>
        `;

        card.addEventListener('click', (e) => {
            e.preventDefault();
            this.openApp(app);
        });

        return card;
    }

    getAppIcon(name, index) {
        const icons = ['🎮', '📚', '🔬', '🎨', '🎵', '🏃', '🧩', '📐'];
        const defaultIcon = icons[index % icons.length];

        const iconMap = {
            '数学': '📐',
            '英语': '📚',
            '科学': '🔬',
            '绘画': '🎨',
            '音乐': '🎵',
            '体育': '🏃',
            '游戏': '🎮',
            '拼图': '🧩'
        };

        for (const [key, icon] of Object.entries(iconMap)) {
            if (name.includes(key)) {
                return icon;
            }
        }

        return defaultIcon;
    }

    openApp(app) {
        if (!app.url) {
            this.showError('应用链接无效');
            return;
        }

        try {
            window.open(app.url, '_blank', 'noopener,noreferrer');
        } catch (error) {
            console.error('打开应用失败:', error);
            this.showError('打开应用失败，请检查链接');
        }
    }

    showEmptyState() {
        this.appContainer.innerHTML = `
            <div class="empty-state">
                <p>暂无可用的应用</p>
            </div>
        `;
    }

    showError(message) {
        this.appContainer.innerHTML = `
            <div class="error">
                <p>${message}</p>
            </div>
        `;
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new AppManager();
});

document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        window.history.back();
    }
});